package com.ywjt.platformbusiness.store.fragment;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseVPFragment;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.home.CommonModel;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.activity.ClassifyActivity;
import com.ywjt.platformbusiness.store.adapter.GoodsUpFragmentAdapter;
import com.ywjt.platformbusiness.store.model.GoodsClassOneModel;
import com.ywjt.platformbusiness.util.JsonUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class GoodUpTypeFragment extends BaseVPFragment implements View.OnClickListener {
    private View view;
    private Context context;
    private List<CommonModel> mTitleList;
    private List<Fragment> fragmentList;
    private RecyclerView rcType;
    private GoodsUpFragmentAdapter typeAdapter;
    private ViewPager viewPager;
    private MainAdapter adapter;
    private LinearLayout llType;

    private int status=0;//0 上架 1 下架


    public static GoodUpTypeFragment newInstance(int status) {
        Bundle arguments = new Bundle();
        arguments.putInt("status",status);
        GoodUpTypeFragment fl = new GoodUpTypeFragment();
        fl.setArguments(arguments);
        return fl;
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.store_goods_type, container, false);
            context = getActivity();
            initView();
        }
        return view;
    }



    public void initView() {
        status=getArguments().getInt("status",0);
        rcType=view.findViewById(R.id.rcType);
        viewPager=view.findViewById(R.id.viewPager);
        llType=view.findViewById(R.id.llType);
        llType.setOnClickListener(this);
    }

    private void getTypeData() {
        new HttpRequest(getContext()).doGet(UrlConstants.classify_getShopTopsideClassify, "", new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                try {
                    String data = result.toString();
                    //把请求得数据转换成json对象
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        Object obj = JsonUtils.fromJson(result.toString(), GoodsClassOneModel.class);
                        if (obj instanceof GoodsClassOneModel) {
                            GoodsClassOneModel model = (GoodsClassOneModel) obj;
                            if (model.getResult().size()>0){
                                mTitleList=new ArrayList<>();
                                fragmentList=new ArrayList<>();
                                for (int i=0;i<model.getResult().size();i++){
                                    if (i==0){
                                        mTitleList.add(new CommonModel(model.getResult().get(i).getName(),true));
                                    }else {
                                        mTitleList.add(new CommonModel(model.getResult().get(i).getName(),false));
                                    }
                                    fragmentList.add(UpGoodsFragment.newInstance(status,model.getResult().get(i).getId()));
                                }

                                typeAdapter=new GoodsUpFragmentAdapter(mTitleList);
                                rcType.setLayoutManager(new LinearLayoutManager(context, RecyclerView.HORIZONTAL,false));
                                rcType.setAdapter(typeAdapter);
                                typeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                        for (int i=0;i<mTitleList.size();i++){
                                            mTitleList.get(i).setSelected(false);
                                        }
                                        mTitleList.get(position).setSelected(true);
                                        typeAdapter.notifyDataSetChanged();
                                        viewPager.setCurrentItem(position);
                                    }
                                });
                                adapter=new MainAdapter(getChildFragmentManager());
                                viewPager.setAdapter(adapter);
                                viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                                    @Override
                                    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                                        for (int i=0;i<mTitleList.size();i++){
                                            mTitleList.get(i).setSelected(false);
                                        }
                                        mTitleList.get(position).setSelected(true);
                                        typeAdapter.notifyDataSetChanged();
                                    }

                                    @Override
                                    public void onPageSelected(int position) {
                                    }

                                    @Override
                                    public void onPageScrollStateChanged(int state) {

                                    }
                                });
                                viewPager.setCurrentItem(0);
                            }

                        }
                    }else {
                        Toast.makeText(getContext(),message,Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                Toast.makeText(getContext(),msg,Toast.LENGTH_SHORT).show();
            }
        });
    }


    @Override
    protected void onFragmentVisibleChange(boolean isVisible) {

    }

    /**
     * 在fragment首次可见时回调，可用于加载数据，防止每次进入都重复加载数据
     */
    @Override
    protected void onFragmentFirstVisible() {
        getTypeData();
    }

    /**
     * Called when a view has been clicked.
     * @param v The view that was clicked.
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.llType:
                //商品分类
                ClassifyActivity.actionStart(context,status);
                break;
        }
    }

    //适配器
    public class MainAdapter extends FragmentPagerAdapter {

        public MainAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        //获取标题
        @Override
        public CharSequence getPageTitle(int position) {
            return mTitleList.get(position).getStr();
        }
    }

}
